﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using VisualAgile.DTO;
using VisualAgile.Model;
using VisualAgile.DTO.Mappers;
using VisualAgile.Controllers;
using System.Collections;
using System.Web.Security;
using VisualAgile.Demo;
using Spring.Context.Support;

namespace ProjectRouting.Controllers
{
    public class ProjectController : BaseController
    {

        public ActionResult Settings()
        {
            return View();
        }

        public ActionResult Calendar()
        {
            return View();
        }           

         // This constructor is used by the MVC framework to instantiate the controller using
        // the default forms authentication and membership providers.
        public ProjectController()
            : this(null, null) {
        }

        // This constructor is not used by the MVC framework but is instead provided for ease
        // of unit testing this type. See the comments at the end of this file for more
        // information.
        public ProjectController(IFormsAuthentication formsAuth, IMembershipService service)
        {
            FormsAuth = formsAuth ?? new FormsAuthenticationService();
            MembershipService = service ?? new AccountMembershipService();            
        }

        // Get: /Home/About
        /// <summary>
        /// Index view for handling project create/retrieve requests from user.
        /// </summary>
        /// <param name="projectName">project name to create or retrieve</param>
        /// <param name="password">passowrd to autehnticate project</param>
        /// <returns>index with project</returns>
        public ActionResult Index(string projectName)
        {
            Project project = null;
            try
            {
                project = ManagerFactory.ProjectManager.GetByName(projectName);    
            }
            catch
            {
                //this block is added for allowing to run demo instance without connecting to Database
                //added for temprary purpose and will be removed.
                project = DemoData.ManagerFactory.ProjectManager.GetByName(projectName);
                SetAuthenticationCookie(FakeUserData.DemoManager().UserID.ToString());
                SetContextUserTo(FakeUserData.DemoManager());
            }                              
            
            User currentUser = null;
            IList users = new List<User>();

            if (CurrentUser != null && CurrentUser.Project.Name != projectName)
            {
                Session.Remove("ManagerFactory");
                RemoveAuthenticationCookie();
                SetContextUserTo(null);
            }

            //create one, if not found
            if (project == null)
            {
                project = ManagerFactory.ProjectManager.NewProject();
                project.Name = projectName;
                project.Creator = projectName;
                project = ManagerFactory.ProjectManager.Save(project);

                //create default user the project
                User user = ManagerFactory.UserManager.NewUser();
                user.Project = project;
                user.Role = ManagerFactory.RoleManager.GetById(1);
                user = ManagerFactory.UserManager.SaveUser(user);
                currentUser = user;
            }
            else
            {
                users = ManagerFactory.UserManager.GetByProject(project.ID);
                
                if (users.Count == 1 && String.IsNullOrEmpty(((User)users[0]).Password))
                    currentUser = users[0] as User;
                else if (users.Count > 1)
                {
                    IList<SelectListItem> usersList = new List<SelectListItem>();                    
                    foreach (User user in users)
                    {                        
                        SelectListItem item = new SelectListItem()
                        {
                            Text = user.UserName,
                            Value = user.UserID.ToString()
                        };

                        usersList.Add(item);
                    }
                    ViewData["Users"] = usersList;
                }
            }

            ViewData["Title"] = project.Name;
            ViewData["projectId"] = project.ID;
            ViewData["allowDefaults"] = true;            

            //authenticate project
            if (currentUser != null)
            {
                SetAuthenticationCookie(currentUser.UserID.ToString());               
            }
            else if (CurrentUser != null && CurrentUser.Identity.IsAuthenticated)
                currentUser = CurrentUser;
            else 
                ViewData["authenticate"] = true;

            return View("Index");
        }       
    }
}
